<template>
    <el-button plain @click="Eject.dialogFormVisible = true">
    新增
  </el-button>
    <div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column  prop="requisitionNum" label="生产编号" />
        <el-table-column prop="requisitionName" label="生产名称"  />
        <el-table-column prop="requisitionOrder" label="生产工单"  />
       
        <el-table-column prop="customerId" label="客户编号"  />

        <el-table-column prop="customerTime" label="入库日期" width="180">
        <template #default="scope">
          {{ scope.row.customerTime.substring(0, 10) }}
        </template>
      </el-table-column>
       
        <el-table-column  prop="customer_name" label="客户名称" />
       
        <el-table-column prop="documentstatus" label="状态"  />
      

        <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
         
          <el-button link type="primary" size="small" @click="xiu(scope.row)"
            >预览</el-button>
           
        </template>
      </el-table-column>
       
      </el-table>
      <tr>
        <td>
          <el-pagination
      v-model:current-page="p.index"
      v-model:page-size="p.size"
      :page-sizes="[10, 20, 30, 40]"
     
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="p.totalCount"
      @size-change="getMenus()"
      @current-change="getMenus()"
    />
        </td>
        <!-- 新增 -->
        <td>
  <el-dialog
    v-model="Eject.dialogFormVisible"
    title="新增"
    width="1000"
    :before-close="handleClose"
  >
    <span>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <div class="form-row">
          <el-form-item label="编号:" :label-width="Eject.formLabelWidth">
            <el-input
              v-model="ruleForm.requisitionNum"
              autocomplete="off"
              style="width: 180px; height: 30px"
              :readonly="ruleForm.autoGenerate"
              clearable
              @click.native="handleCodeClick"
            />
            <template #prepend>MO</template>
            <el-switch
              width="40"
              v-model="ruleForm.autoGenerate"
              active-text="自动生成"
              active-color="#67C23A"
              @change="handleSwitchChange"
            />
          </el-form-item>
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
          <el-form-item label="生产名称" prop="requisitionName" style="flex: 1; margin-right: 10px;">
            <el-input v-model="ruleForm.requisitionName" />
          </el-form-item>
        
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
          <el-form-item label="生产工单" prop="requisitionOrder" style="flex: 1; margin-right: 10px;">
            <el-input v-model="ruleForm.requisitionOrder" />
            <el-button type="primary"  @click="product()">新增</el-button>
          </el-form-item>
          <el-form-item label="客户编号" prop="customerId" style="flex: 1;">
            <el-input v-model="ruleForm.customerId" />
          </el-form-item>
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
          <el-form-item label="客户名称" prop="customer_name" style="flex: 1; margin-right: 10px;">
            <el-input v-model="ruleForm.customer_name" />
          </el-form-item>
      
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
            <el-form-item label="需求日期" required style="flex: 1; margin-right: 10px;">
            <el-date-picker
              v-model="ruleForm.customerTime"
              type="date"
              aria-label="Pick a date"
              placeholder="Pick a date"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="状态" prop="resource">
    <el-radio-group v-model="ruleForm.documentstatus">
      <el-radio label="开"></el-radio>
      <el-radio label="关"></el-radio>
    </el-radio-group>
  </el-form-item>
        
          <!-- <el-form-item label="状态" prop="documentstatus" style="flex: 1;">
            <el-radio v-model="ruleForm.documentstatus" />
          </el-form-item> -->
        </div>
       
        <el-form-item>
          <el-button type="primary" @click="submitForm()">
            添加
          </el-button>
          <el-button @click="handleClose()">关闭</el-button>
        </el-form-item>
      </el-form>
    </span>
  </el-dialog>
</td>    
<!-- 修改 -->
<td>
  <el-dialog
    v-model="Eject.edialogFormVisible"
    title="修改"
    width="1000"
    :before-close="handleClose"
  >
    <span>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <div class="form-row">
          <el-form-item label="编号:" :label-width="Eject.formLabelWidth">
            <el-input
              v-model="ruleForm.requisitionNum"
              autocomplete="off"
              style="width: 180px; height: 30px"
              :readonly="ruleForm.autoGenerate"
              clearable
              @click.native="handleCodeClick"
            />
            <template #prepend>MO</template>
            <el-switch
              width="40"
              v-model="ruleForm.autoGenerate"
              active-text="自动生成"
              active-color="#67C23A"
              @change="handleSwitchChange"
            />
          </el-form-item>
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
          <el-form-item label="生产名称" prop="requisitionName" style="flex: 1; margin-right: 10px;">
            <el-input v-model="ruleForm.requisitionName" />
          </el-form-item>
        
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
          <el-form-item label="生产工单" prop="requisitionOrder" style="flex: 1; margin-right: 10px;">
            <el-input v-model="ruleForm.requisitionOrder" />
          </el-form-item>
          <el-form-item label="客户编号" prop="customerId" style="flex: 1;">
            <el-input v-model="ruleForm.customerId" />
          </el-form-item>
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
          <el-form-item label="客户名称" prop="customer_name" style="flex: 1; margin-right: 10px;">
            <el-input v-model="ruleForm.customer_name" />
          </el-form-item>
      
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
            <el-form-item label="需求日期" required style="flex: 1; margin-right: 10px;">
            <el-date-picker
              v-model="ruleForm.customerTime"
              type="date"
              aria-label="Pick a date"
              placeholder="Pick a date"
              style="width: 100%"
            />
          </el-form-item>


        
          <el-form-item label="状态" prop="resource">
    <el-radio-group v-model="ruleForm.documentstatus">
      <el-radio label="开"></el-radio>
      <el-radio label="关"></el-radio>
    </el-radio-group>
  </el-form-item>
        </div>
       
        <el-form-item>
          <el-button type="primary" @click="update()">
            修改
          </el-button>
          <el-button @click="handleClose()">关闭</el-button>
        </el-form-item>
      </el-form>
      <td>
  <div>
        <el-table :data="aa" style="width: 100%">
          <el-table-column prop="itemnumber" label="物料编号"  />
        <el-table-column prop="boMunit" label=" BOM单位"  />
        <el-table-column prop="boMmaterial" label=" BOM物资"  />
        <el-table-column prop="expectedUsage" label="预计使用量"  />
        <el-table-column  prop="bomType" label="规格型号" />
        <el-table-column label="操作" >
      <template #default="scope">
         
          <el-button link type="primary" size="small" @click="yulan(scope.row)"
            >预览</el-button>
           
        </template>
    </el-table-column>
          </el-table>
          <!-- 分页 -->
          <td>
          <el-pagination
      v-model:current-page="pp.index"
      v-model:page-size="pp.size"
      :page-sizes="[10, 20, 30, 40]"
     
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pp.totalCount"
      @size-change=" BOM()"
      @current-change="BOM()"
    />
        </td>
      </div>
</td>
    </span>
  </el-dialog>
</td>    
<td>

  <div>
        <el-dialog v-model="dialogFormVisible3" title="显示生产工单" width="1000">
            <div style="margin-top: 20px; width: 100%">
                <el-form :inline="true" :model="ruleForm" style="font-size: 15px; width: 100%" class="query-form">
                    <el-form-item label="工单编号" style="margin-left: 30px">
                        <el-input v-model="page3.workOrderCoding" />
                    </el-form-item>
                    <el-form-item label="工单名称" style="margin-left: 20px">
                        <el-input v-model="page3.workOrderName" />
                    </el-form-item>
                    <el-form-item label="产品编号" style="margin-left: 20px">
                        <el-input v-model="page3.productNumber" />
                    </el-form-item>
                    <el-form-item label="产品名称" style="margin-left: 20px">
                        <el-input v-model="page3.productName" />
                    </el-form-item>
                    <el-form-item label="客户名称" style="margin-left: 20px">
                        <el-input v-model="page3.customerNamwe" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="fetchData3">查询</el-button>
                        <el-button type="primary" @click="empty3">清空</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <el-table :data="tableData2" border style="width: 100%">
                <el-table-column label="选择" width="30">
                    <template #default="scope">
                        <el-radio v-model="selectedRow" :label="scope.row"></el-radio>
                    </template>
                </el-table-column>
                <el-table-column prop="workOrderCoding" label="工单编号" />
                <el-table-column prop="workOrderName" label="工单名称" />
                <el-table-column prop="workOrderType" label="工单来源" />
                <el-table-column prop="orderNumber" label="订单编号" />
                <el-table-column prop="productNumber" label="产品编号" />
                <el-table-column prop="productName" label="产品名称" />
                <el-table-column prop="specifications" label="规格型号" />
                <el-table-column prop="unit" label="单位" />
                <el-table-column prop="customerCode" label="客户编码" />
                <el-table-column prop="customerNamwe" label="客户名称" />
            </el-table>
            <div>
                <el-pagination v-model:current-page="page3.index" v-model:page-size="page3.size"
                    :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper"
                    :total="page3.totalCount" @size-change="handleSizeChange3" @current-change="handleCurrentChang3" />
            </div>
            <el-button type="primary" @click="AddGongdan()">确定</el-button>
            <el-button type="primary" @click="dialogFormVisible3 = false">取消</el-button>
        </el-dialog>

    </div>
      <!-- 预览 -->
      <td>
  <el-dialog
    v-model="Eject.yydialogFormVisible"
    title="预览"
    width="1000"
    :before-close="handleClose"
  >
    <span>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
      
        <div class="form-row" style="display: flex; justify-content: space-between;">
          <el-form-item label="物料编号" prop="itemnumber" style="flex: 1; margin-right: 10px;">
            <el-input v-model="ruleForms.itemnumber" />
          </el-form-item>
        
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
          <el-form-item label="生产工单" prop="itemnumber" style="flex: 1; margin-right: 10px;">
            <el-input v-model="ruleForms.itemnumber" />
          </el-form-item>
          <el-form-item label="BOM单位" prop="boMunit" style="flex: 1;">
            <el-input v-model="ruleForms.boMunit" />
          </el-form-item>
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
          <el-form-item label="BOM物资" prop="boMmaterial" style="flex: 1; margin-right: 10px;">
            <el-input v-model="ruleForms.boMmaterial" />
          </el-form-item>
      
        </div>
        <div class="form-row" style="display: flex; justify-content: space-between;">
           
          <el-form-item label="预计使用量" prop="expectedUsage" style="flex: 1;">
            <el-input v-model="ruleForms.expectedUsage" />
          </el-form-item>
          <el-form-item label="规格型号" prop="bomType" style="flex: 1;">
            <el-input v-model="ruleForms.bomType" />
          </el-form-item>
        </div>
       
        <el-form-item>
         
          <el-button @click="handleClose()">关闭</el-button>
        </el-form-item>
      </el-form>
    </span>
  </el-dialog>
</td>    
  </td>
      </tr>

    </div>
  

  </template>
  

  <script setup lang="ts">
  import axios from "axios";
  import { ElMessage, ElMessageBox } from "element-plus";
  import moment from "moment";
  import { onMounted, reactive, ref, watch } from "vue";
  import { useRouter, useRoute } from "vue-router";
  import { useCounterStore } from "@/stores/counter";
  const apiUrl = import.meta.env.VITE_APP_API_URL;
  const dialogFormVisible3 = ref(false);
  const router = useRouter();
  const store = useCounterStore();
  const tableData = ref([]);
  onMounted(() => {
    getMenus();
  });
  
  // 查询表单数据
  const page3 = reactive({
    index: 1,
    size: 10,
    totalCount: 0,
    totalPage: 0,
    workOrderCoding: '',
    workOrderName: '',
    productNumber: '',
    productName: '',
    customerNamwe: '',
  });
  
  // 整合生产工单、查询和分页的方法
  const fetchData3 = () => {
    axios.get(apiUrl+"/T5/Works/GetWorkOrder", { params: page3 })
      .then((res) => {
        tableData2.value = res.data.data;
        page3.totalCount = res.data.totalCount;
        page3.totalPage = res.data.totalPage;
      })
      .catch(error => {
        console.error('获取生产工单失败:', error);
        ElMessage.error('获取生产工单失败');
      });
  };
  const handleSizeChange3 = (val: number) => {
    page3.size = val;
    fetchData3();
  };
  const handleCurrentChang3 = (val: number) => {
    page3.index = val;
    fetchData3();
  };
  const empty3 = () => {
    page3.workOrderCoding = '';
    page3.workOrderName = '';
    page3.productNumber = '';
    page3.productName = '';
    page3.customerNamwe = '';
    fetchData3();
  };
  
  const product = () => {
    dialogFormVisible3.value = true;
    fetchData3();
  };
  
  const tableData2 = ref([]);
  const selectedRow = ref(); // 用于存储选中的行
  
  const AddGongdan = () => {
    if (selectedRow.value) {
      sessionStorage.setItem('WorkOrder', JSON.stringify(selectedRow.value));
      console.log('选中的数据已存入 sessionStorage', sessionStorage.getItem('WorkOrder'));
    } else {
      ElMessage.warning('请选择一条生产任务数据');
      return;
    }
    dialogFormVisible3.value = false;
    const selectedTaskData = sessionStorage.getItem('WorkOrder');
    if (selectedTaskData) {
      const task = JSON.parse(selectedTaskData);
      if (task.workOrderCoding) {
        ruleForm.requisitionOrder = task.workOrderCoding;
        ruleForm.customerId = task.customerCode;
        ruleForm.customer_name = task.customerNamwe;
        console.log('生产任务字段已反填:', ruleForm.requisitionOrder);
      }
    }
  };
  
  const p = reactive({
    index: 1,
    size: 5,
    totalCount: 0,
    totalPage: 0,
  });
  
  // 显示列表
  const getMenus = () => {
    axios({
      url:apiUrl+"/T5/Requisitions/Requisition",
      method: "get",
      params: p
    })
    .then((res) => {
      console.log(res.data.data);
      tableData.value = res.data.data;
      p.totalCount = res.data.totalCount; 
      p.totalPage = res.data.totalPage; 
    })
    .catch(error => {
      console.error('获取列表失败:', error);
      ElMessage.error('获取列表失败');
    });
  };
  
  /// 新增功能修复
  const handleClose = () => {
    Eject.dialogFormVisible = false;
    Eject.edialogFormVisible = false;
    Eject.yydialogFormVisible = false;
    // 重置表单（避免编辑后残留数据）
    ruleForm.requisitionid = "";
    ruleForm.requisitionNum = "";
    ruleForm.requisitionName = "";
    ruleForm.requisitionOrder = "";
    ruleForm.workstation = "";
    ruleForm.customerId = "";
    ruleForm.customer_name = "";
    ruleForm.customerTime = "";
    ruleForm.documentstatus = "";
    ruleForm.autoGenerate = false;
  };
  
  // 修复：新增时不应包含requisitionid（后端生成ID）
  const ruleForm = reactive({
    // 移除requisitionid（新增时不需要ID）
    requisitionNum: "",
    requisitionName: "",
    requisitionOrder: "",
    workstation: "",
    customerId: "",
    customer_name: "",
    customerTime: "",
    documentstatus: "",
    autoGenerate: false, // 是否自动生成
  });
  
  const submitForm = () => {
    // 校验必填字段
    if (!ruleForm.requisitionName.trim()) {
      ElMessage.error('生产名称为必填项');
      return;
    }
    if (!ruleForm.requisitionOrder.trim()) {
      ElMessage.error('生产工单为必填项');
      return;
    }
    if (!ruleForm.customerId.trim()) {
      ElMessage.error('客户编号为必填项');
      return;
    }
    if (!ruleForm.customer_name.trim()) {
      ElMessage.error('客户名称为必填项');
      return;
    }
    if (!ruleForm.customerTime) {
      ElMessage.error('需求日期为必填项');
      return;
    }
  
    axios({
      url: apiUrl+"/T6/Requisitions/AddRequisitons",
      method: 'post',
      data: ruleForm // 移除了无效的requisitionid字段
    })
    .then((res) => {
      if (res.data.code === 100) {
        ElMessage.success("添加成功");
        getMenus();
        Eject.dialogFormVisible = false;
      } else {
        ElMessage.error(`添加失败：${res.data.message || '未知错误'}`);
      }
    })
    .catch(error => {
      console.error('添加请求失败:', error);
      ElMessage.error('添加失败，请检查网络或重试');
    });
  };
  
  const Eject = reactive({
    dialogFormVisible: false,
    formLabelWidth: "100px",
    title: "",
    Isture: true,
    edialogFormVisible: false,
    yydialogFormVisible: false,
  });
  
  // 生成编号逻辑（保持不变）
  const generateCode = () => {
    const timestamp = Date.now(); // 获取精确到毫秒的时间戳
    ruleForm.requisitionNum = `ISSUE${timestamp}`;
  };
  
  const handleSwitchChange = (val: boolean) => {
    ruleForm.autoGenerate = val;
    if (val) {
      generateCode(); // 开启自动生成时立即生成
    } else {
      ruleForm.requisitionNum = ""; // 关闭时清空编号
    }
  };
  
  const handleCodeClick = () => {
    if (ruleForm.autoGenerate) {
      generateCode(); // 点击输入框时重新生成
    }
  }; 
  
  // 编辑功能（修复：确保编辑时正确处理ID）
  const xiu = (row: any) => {
    Eject.edialogFormVisible = true;
    BOM();
    // 编辑时保留requisitionid（与新增区分）
    ruleForm.requisitionid = row.requisitionid; 
    ruleForm.requisitionNum = row.requisitionNum;
    ruleForm.requisitionName = row.requisitionName;
    ruleForm.requisitionOrder = row.requisitionOrder;
    ruleForm.workstation = row.workstation;
    ruleForm.customerId = row.customerId;
    ruleForm.customer_name = row.customer_name;
    ruleForm.customerTime = row.customerTime;
    ruleForm.documentstatus = row.documentstatus;
    ruleForm.autoGenerate = row.autoGenerate;
  };
  
  const update = () => {
    axios({
      
      url:apiUrl+"/T6/Requisitions/UPdateRequisitions",
      method: 'put',
      data: ruleForm
    }).then(res => {
      if (res.data.code === 206) {
        ElMessage.success("修改成功");
        getMenus();
        Eject.edialogFormVisible = false;
      } else {
        ElMessage.error(`修改失败：${res.data.message || '未知错误'}`);
      }
    })
    .catch(error => {
      console.error('修改请求失败:', error);
      ElMessage.error('修改失败，请检查网络或重试');
    });
  };
  
  const aa = ref([]);
  const pp = reactive({
    index: 1,
    size: 3,
    totalCount: 0,
    totalPage: 0
  });
  
  const BOM = () => {
    axios({
      url: apiUrl+"/T5/BOM/GetBOM",
      method: "get",
      params: pp
    })
    .then((res) => {
      console.log(res.data.data);
      aa.value = res.data.data;
      pp.totalCount = res.data.totalCount; 
      pp.totalPage = res.data.totalPage; 
    })
   
  };
  
  // BOM预览
  const ruleForms = reactive({
    bomId: "",
    itemnumber: "",
    boMunit: "",
    boMmaterial: "",
    expectedUsage: "",
    bomType: "",
  });
  
  const yulan = (row: any) => {
    Eject.yydialogFormVisible = true;
    ruleForms.bomId = row.bomId;
    ruleForms.itemnumber = row.itemnumber;
    ruleForms.boMunit = row.boMunit;
    ruleForms.boMmaterial = row.boMmaterial;
    ruleForms.expectedUsage = row.expectedUsage;
    ruleForms.bomType = row.bomType;
  };
  </script>
  
  <style scoped>
  </style>